package com.codeerror.demo.ui.Activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.codeerror.demo.MainActivity;
import com.codeerror.demo.ParallaxDecoration;
import com.codeerror.demo.R;
import com.codeerror.demo.adapter.StarRecyclerAdapter;
import com.codeerror.demo.bean.Star;
import com.codeerror.demo.ui.fragment.CardDialogFragment;
import com.codeerror.demo.util.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class StarActivity extends AppCompatActivity {
    private int numOfBalloon;
    private RecyclerView starRecycler;
    private TextView textView;
    private final StarRecyclerAdapter adapter = new StarRecyclerAdapter();
    private List<Star> stars = new ArrayList<>();
    private final int[] bitmapResources = {
            R.drawable.bg1,
            R.drawable.bg2,
            R.drawable.bg3,
            R.drawable.bg4,
            R.drawable.bg5,
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSysBarTransparent(this);
        setContentView(R.layout.activity_star);
        textView = findViewById(R.id.number_text);
        starRecycler = findViewById(R.id.star_recycler);
        //尝试从SharedPreference中获取星星列表和气球数量
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String starJson = prefs.getString("starJson", null);
        if (starJson == null) {
            initStars();
        } else {
            stars = JsonUtil.jsonToObject(starJson);
        }
        numOfBalloon = prefs.getInt("balloonNumber",50);
        String s = numOfBalloon + "";
        textView.setText(s);
        //初始化
        initRecycler();
        initEvent();
    }
    /**
     * 初始化星球List
     */
    private void initStars() {
        stars.add(new Star(0, R.drawable.s0));
        stars.add(new Star(1, R.drawable.s1));
        stars.add(new Star(2, R.drawable.s2));
        stars.add(new Star(3, R.drawable.s3));
        stars.add(new Star(4, R.drawable.s4));
        stars.add(new Star(5, R.drawable.s5));
        stars.add(new Star(6, R.drawable.s6));
        stars.add(new Star(7, R.drawable.s7));
        stars.add(new Star(8, R.drawable.s8));
        stars.add(new Star(9, R.drawable.s9));
    }


    /**
     * 设置星球点击事件
     */
    private void initEvent() {
        adapter.setOnItemClickListener((view, position, star) -> {
            if (!star.isUnlocked) {//没有解锁，弹出对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog alertDialog = builder.create();
                Objects.requireNonNull(alertDialog).getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                View diaView = getLayoutInflater().inflate(R.layout.fragment_dialog_sure,null);
                alertDialog.setView(diaView);
                TextView yesBtn = diaView.findViewById(R.id.yes_btn);
                TextView noBtn = diaView.findViewById(R.id.no_btn);
                yesBtn.setOnClickListener(v -> {
                    if(numOfBalloon < 20){
                        Toast.makeText(StarActivity.this, "滚！气球够不够心里没点B数？", Toast.LENGTH_SHORT).show();
                    }else {
                        numOfBalloon -= 20;
                        Toast.makeText(StarActivity.this, "解锁成功", Toast.LENGTH_SHORT).show();
                        String s = numOfBalloon + "";
                        textView.setText(s);
                        CardDialogFragment cdf = new CardDialogFragment(star.id);//这个id是对应position的star的id
                        FragmentManager fm = getSupportFragmentManager();
                        cdf.show(fm, "CardDialogFragment");
                        star.isUnlocked = true;
                        view.findViewById(R.id.locked_star_image).setVisibility(View.INVISIBLE);
                    }
                    alertDialog.dismiss(); // 取消对话框
                });
                noBtn.setOnClickListener(v -> alertDialog.dismiss());
                alertDialog.show();// 显示对话框
            } else {
                CardDialogFragment cdf = new CardDialogFragment(star.id);//这个id是对应position的star的id
                FragmentManager fm = getSupportFragmentManager();
                cdf.show(fm, "CardDialogFragment");
            }
        });
    }



    /**
     * 初始化星球Recycler
     */
    private void initRecycler() {
        //配置itemDecoration
        ParallaxDecoration parallaxDecoration = new ParallaxDecoration(this);
        parallaxDecoration.setParallax(0.7f);
        parallaxDecoration.decodeBitmap(bitmapResources);
        starRecycler.addItemDecoration(parallaxDecoration);
        //配置adapter
        adapter.setStars(stars);
        starRecycler.setAdapter(adapter);
        //配置layoutManager
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        starRecycler.setLayoutManager(linearLayoutManager);
    }


    /**
     * 设置设置沉浸式状态栏
     */
    public static void setSysBarTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }


    /**
     * 保存星球解锁与否的状态
     */
    private void saveState() {
        String starJson = JsonUtil.objectToJson(stars);
        Log.e("MAIN", "onDestroy: " + starJson);
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putString("starJson", starJson);
        editor.putInt("balloonNumber", numOfBalloon);
        editor.apply();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        saveState();
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }
}